import { promisify } from 'util';
import * as path from 'path';
import * as cp from 'child_process';
import * as fs from 'fs';
import * as rmdir from 'rmdir';
import { globalConfig } from '../config/globalConfig';
let qn = require('qn');
import * as dayjs from 'dayjs';

let client = qn.create({
    accessKey: 'spnciVyx1RlmsrUOncnhlUXkqc2-VFLOgiOEcpc5',
    secretKey: 'cv6vQI6U9S-nYq_zdiPmNiYzHfzIsXig2CPjIXcj',
    bucket: 'mongodb-dump-storage',
    origin: 'otdzjy0ga.bkt.clouddn.com',
});

// 备份数据库
async function dumpMongodb(): Promise<[string, string]> {
    let file = path.join(__dirname, './dump.sh');
    let timeStamp = `${globalConfig.databaseName}-${dayjs().format(
        'YYYYMMDDhhmmss',
    )}`;

    // 创建backup目录
    let backupPath = path.join(__dirname, '../../backup');
    if (!(await promisify(fs.exists)(backupPath))) {
        await promisify(fs.mkdir)(backupPath);
    }

    return new Promise<[string, string]>((resolve, reject) => {
        // 测试环境下不做备份
        if (globalConfig.isDebug) {
            console.log('测试模式 不需要备份');
            return reject();
        }
        cp.exec(`sh ${file} ${globalConfig.databaseName} ${timeStamp}`, err => {
            err
                ? reject(err)
                : resolve([
                    `${timeStamp}.zip`,
                    path.join(__dirname, `../../backup/${timeStamp}.zip`)]);
        });
    });
}

// 上传文件到七牛云
function uploadFile(filename: string, filepath: string): Promise<void> {
    return new Promise<void>((resolve, reject) => {
        client.uploadFile(
            filepath,
            {
                key: filename,
            },
            async (err, res) => {
                err ? reject(err) : resolve();

                // 删除备份文件和文件夹
                await promisify(fs.unlink)(filepath);
                await promisify(rmdir)(filepath.slice(0, filepath.length - 4));
            },
        );
    });
}

export async function dumpMongodbTask() {
    console.log('开始备份');
    let [filename, filepath] = await dumpMongodb();
    await uploadFile(filename, filepath);
    console.log('备份成功');
}
